package com.wechet.controller;

import com.wechet.VO.ProductInfoVo;
import com.wechet.VO.ProductVo;
import com.wechet.VO.ResultVo;
import com.wechet.common.ProductStatus;
import com.wechet.common.ResultStatus;
import com.wechet.domain.ProductCategory;
import com.wechet.domain.ProductInfo;
import com.wechet.serveice.impl.ProductCategoryServiceImpl;
import com.wechet.serveice.impl.ProductInfoServiceImpl;
import com.wechet.utils.ResultVoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by sc on 2017/9/20.
 */

@RestController
@RequestMapping("/buyer/product")
public class BuyProductController {

    @Autowired
    private ProductInfoServiceImpl productInfoService;

    @Autowired
    private ProductCategoryServiceImpl productCategoryService;

    @GetMapping("/list")
    @Cacheable(cacheNames = "product", key = "123")
    public ResultVo list(){
        //1.查询所有上架商品
        List<ProductInfo> productInfoList =  productInfoService.findUpAll();


        //2.按类目查询 lambda
        List<Integer> categoryTypeList = productInfoList.stream().map(e->e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeList);

        //拼装数据
        List<ProductVo> productVoList = new ArrayList<>();
        for(ProductCategory productCategory:productCategoryList){
            ProductVo productVo= new ProductVo();
            productVo.setCategoryName(productCategory.getCategoryName());
            productVo.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVo> productInfoVoList = new ArrayList<>();
            for(ProductInfo productInfo :productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo,productInfoVo);
                    productInfoVoList.add(productInfoVo);
                }
            }
            productVo.setProductInfoVoList(productInfoVoList);
            productVoList.add(productVo);
        }

        return ResultVoUtil.success(productVoList);
    }
}
